package com.lagou.study.controller;

import cn.hutool.core.util.RandomUtil;
import com.lagou.study.pojo.LagouAuthCode;
import com.lagou.study.service.CodeService;
import com.lagou.study.service.EmailService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("code")
public class CodeController {

    @Reference
    private EmailService emailService;

    @Autowired
    private CodeService codeService;

    @PostMapping("create")
    public boolean create(String email){
        String randomCode = RandomUtil.randomString("0123456789", 6);
        LagouAuthCode lagouAuthCode = codeService.saveCode(email, randomCode);
        if(lagouAuthCode!=null){
            emailService.sendCode(email, randomCode);
            return true;
        }else {
            return false;
        }
    }

    @PostMapping("validate")
    public Integer validate(String email, String code){
        Integer result = codeService.validateCodeByEmail(email, code);
        return result;
    }
}
